﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using System.Web.Security;


namespace LightSO.CMS
{
    public static class FormsAuth
    {
        private static Encoding encode = Encoding.UTF8;
        private static string _domain = string.Empty;
        private static int _expiration = 120;
        private static int _rememberDays = 14;


        /// <summary>
        /// 获取验证标志名。
        /// </summary>
        /// <value>验证标志名。</value>
        public static string FormName
        {
            get { return FormsAuthentication.FormsCookieName; }
        }

        /// <summary>
        /// 获取或设置用户身份证书过期时间。
        /// </summary>
        /// <value>用户身份证书过期时间。</value>
        public static int Expiration
        {
            get { return _expiration; }
            set { _expiration = value; }
        }

        /// <summary>
        ///  获取当前访问的主域名。比如：www.abc.com的主域名是:abc.com
        /// </summary>
        private static string Domain
        {
            get
            {
                if (_domain != string.Empty)
                    return _domain;

                Uri url = HttpContext.Current.Request.Url;
                if (url.HostNameType == UriHostNameType.Dns)
                {
                    string host = url.Host.ToLower();
                    string[] nodes = host.Split('.');
                    int len = nodes.Length;
                    if (len >= 2)
                    {
                        _domain = nodes[len - 2].ToString() + "." + nodes[len - 1];
                    }
                }
                return _domain;
            }
        }

        /// <summary>
        /// 获取指定键的Cookie值。
        /// </summary>
        /// <param name="cookieKey"></param>
        /// <returns></returns>
        public static string GetCookie(string cookieKey)
        {
            HttpCookie hc = HttpContext.Current.Request.Cookies[cookieKey];
            return hc == null ? string.Empty : HttpUtility.UrlDecode(hc.Value, encode);
        }

        /// <summary>
        /// 设置Cookie值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCookie(string key, string value)
        {
            value = HttpUtility.UrlEncode(value, encode);
            HttpCookie hc = new HttpCookie(key, value);
            //hc.Domain = Domain;
            HttpContext.Current.Response.AppendCookie(hc);
        }

        /// <summary>
        /// 获取UserData数据，登录时写的验证票
        /// </summary>
        /// <returns></returns>
        public static string GetUserData()
        {
            string userData = string.Empty;
            HttpContext currentContext = HttpContext.Current;
            if (currentContext.User != null)
            {
                if (currentContext.User.Identity is FormsIdentity && currentContext.User.Identity.IsAuthenticated)
                {
                    FormsIdentity id = currentContext.User.Identity as FormsIdentity;
                    FormsAuthenticationTicket ticket = id.Ticket;
                    userData = ticket.UserData;
                }
            }
            return userData;
        }
        /// <summary>
        /// 清除Cookie
        /// </summary>
        public static void ClearCookies()
        {
            for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
            {
                ClearOneCookies(HttpContext.Current.Request.Cookies[i]);
            }
        }

        /// <summary>
        /// 删除一个具体的Cookie
        /// </summary>
        /// <param name="hc"></param>
        private static void ClearOneCookies(HttpCookie hc)
        {
            hc.Expires = DateTime.Now.AddDays(-1);
            //hc.Domain = Domain;
            HttpContext.Current.Response.Cookies.Set(hc);
        }

        /// <summary>
        /// 设置用户身份证书。
        /// </summary>
        /// <param name="name">用户身份标识。</param>
        /// <param name="userData">需要保存在Cookie中的用户数据。</param>
        /// <param name="isPersistent">证书是否长期有效。</param>
        public static void SetAuthTicket(string name, string userData, bool isPersistent)
        {
            DateTime expires = (isPersistent) ? DateTime.Now.AddDays(_rememberDays) : DateTime.Now.AddMinutes(_expiration);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, expires, isPersistent, userData);

            string sEncode = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormName, sEncode);
            cookie.Domain = Domain;
            //if (isPersistent)
            //    cookie.Expires = expires;
            HttpContext.Current.Response.Cookies.Set(cookie);
        }

        /// <summary>
        /// 清除用户身份证书。
        /// </summary>
        public static void SignOut()
        {
            //if (Domain != "")
            //{
                ClearCookies();

                HttpCookie cookie = new HttpCookie(FormName);
                cookie.Domain = Domain;
                cookie.Expires = DateTime.Now.AddYears(-1);
                HttpContext.Current.Response.Cookies.Set(cookie);

                FormsAuthentication.SignOut();
            //}
            //else 
       
        }

        /// <summary>
        /// 根据用户请求页面自动转向。
        /// </summary>
        public static void Redirect()
        {
            HttpContext.Current.Response.Redirect(GetRedirectUrl());
        }

        /// <summary>
        /// 获取导致重定向到登录页的原始请求的重定向URL。
        /// </summary>
        /// <returns>导致重定向到登录页的原始请求的重定向URL。</returns>
        public static string GetRedirectUrl()
        {
            Uri url = HttpContext.Current.Request.UrlReferrer;
            if (url != null)
            {
                return url.ToString();
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取服务器应用程序虚拟路径
        /// by Ocean 2010-12-08
        /// </summary>
        /// <value>服务器应用程序虚拟路径。</value>
        public static string ApplicationPath
        {
            get
            {
                string root = HttpContext.Current.Request.ApplicationPath;
                if (root != "/") root += "/";
                return root;
            }
        }
    }
}
